﻿using System.Web.UI;

using Microsoft.Practices.CompositeWeb.Interfaces;
using Microsoft.Practices.ObjectBuilder;
using WCSFContrib.Extensions.CompositeWeb.ObjectBuilder.Strategies;
using WCSFContrib.Extensions.CompositeWeb.ObjectBuilder;

namespace WCSFContrib.Extensions.CompositeWeb
{
	public class WebClientApplication : Microsoft.Practices.CompositeWeb.WebClientApplication
	{
		/// <summary>
		/// Before the requested <see cref="Page"/> handler is executed create a new RequestEventBroker instance and place in session.
		/// </summary>
		/// <param name="page">The requested <see cref="Page"/>.</param>
		protected override void PrePageExecute(Page page)
		{
			RequestEventBroker.ResetEventBroker();
		}

		/// <summary>
		/// After the requested <see cref="Page"/> handler is executed dispose of the RequestEventBroker instance in session.
		/// </summary>
		/// <param name="page">The requested <see cref="Page"/>.</param>
		protected override void PostPageExecute(Page page)
		{
			RequestEventBroker.Instance.Dispose();
		}

		/// <summary>
		/// Create a builder which inherits <see cref="Microsoft.Practices.CompositeWeb.ObjectBuilder.WCSFBuilder"/>
		/// </summary>
		/// <param name="isSingleton">Is this a singleton builder or not?</param>
		/// <returns>The builder.</returns>
		protected override Microsoft.Practices.CompositeWeb.ObjectBuilder.WCSFBuilder CreateBuilder(bool isSingleton)
		{
			// Our builder adds an EventBrokerStrategy to the build.
			WCSFBuilder builder = new WCSFBuilder();
			builder.Policies.SetDefault<ISingletonPolicy>(new SingletonPolicy(isSingleton));
			return builder;
		}

		/// <summary>
		/// Run the sanity check on all publication and subscription matches.
		/// </summary>
		protected override void Start()
		{
			EventBrokerStrategy.ApplicationPubSubSanityCheck(RootContainer.Services.Get<IModuleEnumerator>());
		}
	}
}